﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Management;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using LY.Common;
using LY.Common.Utils;
using LY.Entity;
using LY.SSOServer.Models;

namespace LY.SSOServer.Controllers
{
    public class SSOController : Controller
    {
        //
        // GET: /SSO/
        protected string turl = string.Empty;
        public ActionResult UserLogin()
        { 
            turl = Request.QueryString["BackURL"]; 
            if (turl == null || turl.Trim().Length == 0)
            {
                turl = "http://www.changerbank.com";
            }
            LY.Common.Utility.WriteCookie(RBSKeys.COOKIE_URL_REFERRER, turl);  
            ViewBag.Mac = CacheManager.GetRemoteMac();
            return View();
        } 
        public WebApiMsg<U_Member> Login(WebApiMsg<LY.Entity.U_Member> jsonData)
        {
            if (jsonData.message == "OK")
            {
                //产生令牌
                string tokenValue = this.GetGuidString();
                HttpCookie tokenCookie = new HttpCookie("Token");
                tokenCookie.Values.Add("Value", tokenValue);
                tokenCookie.Domain = "changerbank.com";
                Response.AppendCookie(tokenCookie);

                //产生主站凭证
                object info = jsonData.data;// jsonData.data;
                CacheManager.TokenInsert(tokenValue, info, DateTime.Now.AddMinutes(double.Parse(System.Configuration.ConfigurationManager.AppSettings["timeout"])));

                jsonData.data = null;

                turl = LY.Common.Utility.GetCookie(RBSKeys.COOKIE_URL_REFERRER);

                if (turl.Contains("retrurnUrl"))
                {
                    jsonData.message = turl + "&Token=" + tokenValue;
                }
                else
                {
                    Regex reg = new Regex(@"^.*\?.+=.+$");
                    if (reg.IsMatch(turl))
                        turl += "&Token=" + tokenValue;
                    else
                        turl += "?Token=" + tokenValue;

                    jsonData.message = turl;
                }
                return jsonData;

            }
            else
            {
                return jsonData;
            }

        }

        [HttpPost]
        public ActionResult UserLogin(FormCollection collection)
        {
            string md5Password = MD5Util.GetMD5_32(collection["txtPassport"]);
            var content = new FormUrlEncodedContent(new[] 
            {
                new KeyValuePair<string, string>("Phone", collection["txtAccount"]),
                new KeyValuePair<string, string>("Password", md5Password)
            });
            var jsonData = ApiRepository<LY.Entity.U_Member>.Post("Member/Login.do", content);

            jsonData = Login(jsonData);
            return Json(jsonData);

        }


        public ActionResult Error(string msg = null)
        {
            return Content(msg);
        }

        public ActionResult AauthLogin()
        {
            turl = LY.Common.Utility.GetCookie(RBSKeys.COOKIE_URL_REFERRER);
            if (turl == null || turl.Trim().Length == 0)
            {
                turl = "http://www.changerbank.com";
            }


            //检查是否已授权
            if (Session["oauth_name"] == null || Session["oauth_access_token"] == null || Session["oauth_openid"] == null)
            {

                return RedirectToAction("Error", new { msg = LY.Common.Utility.UrlEncode("登录失败，用户授权已过期，请重新登录！") });
            }



            var content = new FormUrlEncodedContent(new[] 
            {
                new KeyValuePair<string, string>("oauth_name", Session["oauth_name"].ToString()),
                new KeyValuePair<string, string>("oauth_openid", Session["oauth_openid"].ToString())
            });
            var jsonData = ApiRepository<LY.Entity.U_Member_oauth>.Post("Member/OauthLogin.do", content);

            if (jsonData.status == 1)
            {
                content = new FormUrlEncodedContent(new[] 
                {
                    new KeyValuePair<string, string>("Id", jsonData.data.user_id.ToString()) 
                  
                });
                var jsonData1 = ApiRepository<LY.Entity.U_Member>.Post("Member/LoginName", content);
                //检查用户是否存在 
                if (jsonData1.status != 1)
                {
                    return RedirectToAction("Error", new { msg = LY.Common.Utility.UrlEncode("登录失败，授权用户不存在或已被删除！") });
                }
                jsonData1 = Login(jsonData1);
                return Redirect(jsonData1.message);
            }
            return View();
        }

        [HttpPost]
        public ActionResult user_oauth_bind(FormCollection collection)
        {
            var jsonData = new WebApiMsg<U_Member>();

            //检查URL参数
            if (Session["oauth_name"] == null)
            {
                jsonData.status = 0;
                jsonData.message = "错误提示：授权参数不正确！";
                return Json(jsonData);
            }
            //获取授权信息
            string result = LY.Common.Utility.UrlExecute("/api/oauth/sina/result_json.aspx");
            if (result.Contains("error"))
            {
                jsonData.status = 0;
                jsonData.message = "错误提示：请检查URL是否正确！";
                return Json(jsonData);
            }
            //反序列化JSON
            Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(result);
            if (dic["ret"].ToString() != "0")
            {
                jsonData.status = 0;
                jsonData.message = "错误代码：" + dic["ret"] + "，描述：" + dic["msg"];
                return Json(jsonData);
            }

            //检查用户名密码
            string username = collection["txtUserName"];
            string password = collection["txtPassword"];
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                jsonData.status = 0;
                jsonData.message = "温馨提示：请输入用户名或密码！";
                return Json(jsonData);
            }

            string md5Password = MD5Util.GetMD5_32(password);
            var content = new FormUrlEncodedContent(new[] 
            {
                new KeyValuePair<string, string>("Phone", username),
                new KeyValuePair<string, string>("Password", md5Password)
            });

            var menberjsonData = ApiRepository<LY.Entity.U_Member>.Post("Member/Login.do", content);
            if (menberjsonData.message != "OK")
            {
                jsonData.status = 0;
                jsonData.message = "错误提示：用户名或密码错误！";
                return Json(jsonData);
            }


            content = new FormUrlEncodedContent(new[] 
            {
                new KeyValuePair<string, string>("oauth_name", dic["oauth_name"].ToString()),
                new KeyValuePair<string, string>("user_id", menberjsonData.data.ID.ToString()),
                new KeyValuePair<string, string>("oauth_access_token", dic["oauth_access_token"].ToString()),
               new KeyValuePair<string, string>("oauth_openid",  dic["oauth_openid"].ToString()),
                 new KeyValuePair<string, string>("user_name", menberjsonData.data.Name),
            });
            var memberOautjsonData = ApiRepository<string>.Post("Member/RegMemberOauth.do", content);
            if (menberjsonData.message != "OK")
            {
                jsonData.status = 0;
                jsonData.message = "错误提示：绑定过程中出错，请重新获取！";
                return Json(jsonData);
            }

            jsonData = Login(menberjsonData);
            return Json(jsonData);

        }
        [HttpPost]
        public ActionResult user_oauth_register(FormCollection collection)
        {
            var jsonData = new WebApiMsg<string>();
            //检查URL参数
            if (Session["oauth_name"] == null)
            {
                jsonData.status = 0;
                jsonData.message = "错误提示：授权参数不正确！";
                return Json(jsonData);
            }
            //获取授权信息
            string result = LY.Common.Utility.UrlExecute("/api/oauth/sina/result_json.aspx");
            if (result.Contains("error"))
            {
                jsonData.status = 0;
                jsonData.message = "错误提示：请检查URL是否正确！";
                return Json(jsonData);
            }
            //反序列化JSON
            Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(result);
            if (dic["ret"].ToString() != "0")
            {
                jsonData.status = 0;
                jsonData.message = "错误代码：" + dic["ret"] + "，描述：" + dic["msg"];
                return Json(jsonData);
            }



            string md5Password = MD5Util.GetMD5_32(collection["txtPassword"]);
            var content = new FormUrlEncodedContent(new[] 
                    {
                        new KeyValuePair<string, string>("Phone", collection["txtMobile"]),
                        new KeyValuePair<string, string>("Password", md5Password),
                        new KeyValuePair<string, string>("Email", collection["txtEmail"]),
                        new KeyValuePair<string, string>("headimage", dic["avatar"].ToString()),
                        new KeyValuePair<string, string>("sex",dic["sex"].ToString()),
                        new KeyValuePair<string, string>("Nick_Name", dic["nick"].ToString()),
                        new KeyValuePair<string, string>("birthday", dic["birthday"].ToString()),
                    });
         //   var jsonData = ApiRepository<string>.Post("Member/Register.do", content);
            //if (menberjsonData.message != "OK")
            //{
            //    jsonData.status = 0;
            //    jsonData.message = "错误提示：用户名或密码错误！";
            //    return Json(jsonData);
            //}




            
            ////保存注册信息
            //model.group_id = modelGroup.id;
            //model.user_name = bll.GetRandomName(10); //随机用户名
            //model.salt = Utils.GetCheckCode(6); //获得6位的salt加密字符串
            //model.password = DESEncrypt.Encrypt(password, model.salt);
            //model.email = email;
            //model.mobile = mobile;
            //if (!string.IsNullOrEmpty(dic["nick"].ToString()))
            //{
            //    model.nick_name = dic["nick"].ToString();
            //}
            //if (dic["avatar"].ToString().StartsWith("http://"))
            //{
            //    model.avatar = );
            //}
            //if (!string.IsNullOrEmpty(dic["sex"].ToString()))
            //{
            //    model.sex = dic["sex"].ToString();
            //}
            //if (!string.IsNullOrEmpty(dic["birthday"].ToString()))
            //{
            //    model.birthday = Utils.StrToDateTime(dic["birthday"].ToString());
            //}
            //model.reg_ip = userip;
            //model.reg_time = DateTime.Now;
            //model.status = 0; //设置为正常状态
            //model.id = bll.Add(model); //保存数据
            //if (model.id < 1)
            //{
            //    context.Response.Write("{\"status\":0, \"msg\":\"注册失败，请联系网站管理员！\"}");
            //    return;
            //}
            ////赠送积分金额
            //if (modelGroup.point > 0)
            //{
            //    new BLL.user_point_log().Add(model.id, model.user_name, modelGroup.point, "注册赠送积分", false);
            //}
            //if (modelGroup.amount > 0)
            //{
            //    new BLL.user_amount_log().Add(model.id, model.user_name, modelGroup.amount, "注册赠送金额");
            //}
            ////判断是否发送欢迎消息
            //if (userConfig.regmsgstatus == 1) //站内短消息
            //{
            //    new BLL.user_message().Add(1, "", model.user_name, "欢迎您成为本站会员", userConfig.regmsgtxt);
            //}
            //else if (userConfig.regmsgstatus == 2) //发送邮件
            //{
            //    //取得邮件模板内容
            //    Model.mail_template mailModel = new BLL.mail_template().GetModel("welcomemsg");
            //    if (mailModel != null)
            //    {
            //        //替换标签
            //        string mailTitle = mailModel.maill_title;
            //        mailTitle = mailTitle.Replace("{username}", model.user_name);
            //        string mailContent = mailModel.content;
            //        mailContent = mailContent.Replace("{webname}", siteConfig.webname);
            //        mailContent = mailContent.Replace("{weburl}", siteConfig.weburl);
            //        mailContent = mailContent.Replace("{webtel}", siteConfig.webtel);
            //        mailContent = mailContent.Replace("{username}", model.user_name);
            //        //发送邮件
            //        DTMail.sendMail(siteConfig.emailsmtp, siteConfig.emailssl, siteConfig.emailusername, siteConfig.emailpassword, siteConfig.emailnickname,
            //            siteConfig.emailfrom, model.email, mailTitle, mailContent);
            //    }
            //}
            //else if (userConfig.regmsgstatus == 3 && mobile != "") //发送短信
            //{
            //    Model.sms_template smsModel = new BLL.sms_template().GetModel("welcomemsg"); //取得短信内容
            //    if (smsModel != null)
            //    {
            //        //替换标签
            //        string msgContent = smsModel.content;
            //        msgContent = msgContent.Replace("{webname}", siteConfig.webname);
            //        msgContent = msgContent.Replace("{weburl}", siteConfig.weburl);
            //        msgContent = msgContent.Replace("{webtel}", siteConfig.webtel);
            //        msgContent = msgContent.Replace("{username}", model.user_name);
            //        //发送短信
            //        string tipMsg = string.Empty;
            //        new BLL.sms_message().Send(model.mobile, msgContent, 2, out tipMsg);
            //    }
            //}
            ////绑定到对应的授权类型
            //Model.user_oauth oauthModel = new Model.user_oauth();
            //oauthModel.oauth_name = dic["oauth_name"].ToString();
            //oauthModel.user_id = model.id;
            //oauthModel.user_name = model.user_name;
            //oauthModel.oauth_access_token = dic["oauth_access_token"].ToString();
            //oauthModel.oauth_openid = dic["oauth_openid"].ToString();
            //new BLL.user_oauth().Add(oauthModel);

            //context.Session[DTKeys.SESSION_USER_INFO] = model;
            //context.Session.Timeout = 45;
            ////记住登录状态，防止Session提前过期
            //Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "DTcms", model.user_name);
            //Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "DTcms", model.password);
            ////写入登录日志
            //new BLL.user_login_log().Add(model.id, model.user_name, "会员登录");
            ////返回URL
            //context.Response.Write("{\"status\":1, \"msg\":\"会员登录成功！\"}");
            //return;
            return Json(jsonData);
        }


        /// <summary>
        /// 产生绝对唯一字符串，用于令牌
        /// </summary>
        /// <returns></returns>
        private string GetGuidString()
        {
            return Guid.NewGuid().ToString().ToUpper();
        }

        public ActionResult GetToken()
        {
            if (Request.QueryString["BackURL"] != null)
            {
                string backURL = Server.UrlDecode(Request.QueryString["BackURL"]);

                //获取Cookie
                HttpCookie tokenCookie = Request.Cookies["Token"];
                if (tokenCookie != null)
                {
                    backURL = backURL.Replace("$Token$", tokenCookie.Values["Value"].ToString());
                }

                Response.Redirect(backURL);
            }

            return View();
        }


        public ActionResult CacheList()
        {

            DataTable dt = CacheManager.GetCacheTable();
            var list = new List<TokenList>();
            Int32 recordCount = 0;

            if (dt != null)
            {
                list.AddRange(from DataRow row in dt.Rows select row.ConvertToEntity<TokenList>());
            }
            ViewData.Model = list;
            return View();
        }

    }
}
